"""Manual sequential auth flow test.

Run while the FastAPI server is up (uvicorn app.main:app --reload)
Usage:
    python backend/tests/manual_auth_test.py
"""

from __future__ import annotations

import os
import sys
import time
import json
from typing import Any, Dict

import requests

BASE_URL = os.environ.get("ANCIENT_SEEKER_BASE", "http://127.0.0.1:8000")


def section(title: str):
    print(f"\n{'=' * 12} {title} {'=' * 12}")


def pretty(resp: requests.Response):
    try:
        data = resp.json()
        print("Status:", resp.status_code)
        print(json.dumps(data, ensure_ascii=False, indent=2))
        return data
    except Exception:  # pragma: no cover - manual convenience
        print("Status:", resp.status_code)
        print(resp.text)
        return None


def main():
    section("Guest Login")
    r = requests.post(f"{BASE_URL}/api/auth/guest")
    guest = pretty(r)
    if not r.ok:
        print("Guest login failed, aborting")
        sys.exit(1)
    if not isinstance(guest, dict) or "access_token" not in guest:
        print("Guest response malformed, aborting")
        sys.exit(1)
    guest_token = guest["access_token"]

    section("Guest /me")
    r = requests.get(
        f"{BASE_URL}/api/auth/me", headers={"Authorization": f"Bearer {guest_token}"}
    )
    pretty(r)

    section("Guest change password (should fail)")
    r = requests.put(
        f"{BASE_URL}/api/auth/password",
        json={"old_password": "x", "new_password": "y123456"},
        headers={"Authorization": f"Bearer {guest_token}"},
    )
    pretty(r)

    # Unique user name based on timestamp to allow repeated runs
    username = f"u{int(time.time())}"[-8:]

    section(f"Register user {username}")
    r = requests.post(
        f"{BASE_URL}/api/auth/register",
        json={"username": username, "password": "Pass1234"},
    )
    reg = pretty(r)
    if not r.ok:
        print("Registration failed, aborting")
        return

    section("Duplicate registration (expect 409)")
    r = requests.post(
        f"{BASE_URL}/api/auth/register",
        json={"username": username, "password": "Pass1234"},
    )
    pretty(r)

    section("Login user")
    r = requests.post(
        f"{BASE_URL}/api/auth/login",
        json={"username": username, "password": "Pass1234"},
    )
    login = pretty(r)
    if not r.ok:
        print("Login failed, aborting")
        return
    if not isinstance(login, dict) or "access_token" not in login:
        print("Login response malformed, aborting")
        return
    user_token = login["access_token"]

    section("/me with user token")
    r = requests.get(
        f"{BASE_URL}/api/auth/me", headers={"Authorization": f"Bearer {user_token}"}
    )
    pretty(r)

    section("Change password")
    r = requests.put(
        f"{BASE_URL}/api/auth/password",
        json={"old_password": "Pass1234", "new_password": "NewPass5678"},
        headers={"Authorization": f"Bearer {user_token}"},
    )
    pretty(r)

    section("Login with old password (expect 401)")
    r = requests.post(
        f"{BASE_URL}/api/auth/login",
        json={"username": username, "password": "Pass1234"},
    )
    pretty(r)

    section("Login with new password")
    r = requests.post(
        f"{BASE_URL}/api/auth/login",
        json={"username": username, "password": "NewPass5678"},
    )
    pretty(r)

    # section("Logout (stateless)")
    # r = requests.post(f"{BASE_URL}/api/auth/logout")
    # pretty(r)

    # print("\nFlow complete.")


if __name__ == "__main__":
    main()
